package com.iwhalecloud.bss.kite.cucc.service.pos.bcmc.handler.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.ILocalQueryScenePersonInfoService;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.KiteCustomerInfoReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosCustomerDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDetailDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CustAttrDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.pos.bcmc.BcmcPosContext;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

/**
 * <Description> <br>
 * 组装报文客户信息节点
 * 
 * @author XXZ<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2020年12月15日 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.service.pos.bcmc.handler.impl <br>
 */
@Service
public class BcmcPosCustomerHandler extends AbstractBcmcPosHandler {

    @Autowired
    private ICustReceptionService custReceptionService;

    @Autowired
    private ILocalQueryScenePersonInfoService queryScenePersonService;

    @Override
    public void doHandle(BcmcPosContext context) {
        CuccContextCustDTO custDto = context.getCustDto();
        KitePosCustomerDTO customer = new KitePosCustomerDTO();
        String sceneInstId = context.getSceneInstId();
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());
        String createDateStr = KiteDateUtils.formatDate(kiteSceneInst.getCreateDate(),
            KiteDateUtils.DATE_TIME_FORMAT_14);
        if (!ServiceOfferConsts.SERVICE_OFFER_TRANSFER.equals(kiteSceneInst.getServiceOfferId())) {
            KiteBeanUtils.copyProperties(custDto, customer);
            customer.setName(custDto.getCustName());
            customer.setEparchyCity(Optional.ofNullable(custDto.getLanId()).orElse(custDto.getEparchyCode()));
            customer.setEparchyArea(custDto.getRegionId());
            customer.setEparchyProvince(custDto.getProvinceCode());
            customer.setCustType(custDto.getCustType());
            customer.setBssId(custDto.getBbssCustId());
            customer.setCbssId(custDto.getCbssId());
//            customer.setContactPhone("18019283745");

            if (Objects.isNull(customer.getAttrs())) {
                customer.setAttrs(new ArrayList<>());
            }

            List<KitePosAttrDTO> custStateAttr = customer.getAttrs().stream()
                .filter(attr -> KiteStringUtils.equals("custState", attr.getCode())).collect(Collectors.toList());
            if (KiteListUtils.isEmpty(custStateAttr)) {
                KitePosAttrDTO custState = new KitePosAttrDTO();
                custState.setCode("custState");
                custState.setValue("0");
                custState.setStartDate(createDateStr);
                custState.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
                customer.getAttrs().add(custState);
            }
            List<KitePosAttrDTO> certiTypeCodeAttr = customer.getAttrs().stream()
                .filter(attr -> KiteStringUtils.equals("certiTypeCode", attr.getCode())).collect(Collectors.toList());
            if (KiteListUtils.isEmpty(certiTypeCodeAttr)) {
                KitePosAttrDTO custState = new KitePosAttrDTO();
                custState.setCode("certiTypeCode");
                custState.setValue(custDto.getCertiTypeCode());
                custState.setStartDate(createDateStr);
                custState.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
                customer.getAttrs().add(custState);
            }
            List<KitePosAttrDTO> certiCodeAttr = customer.getAttrs().stream()
                .filter(attr -> KiteStringUtils.equals("certiCode", attr.getCode())).collect(Collectors.toList());
            if (KiteListUtils.isEmpty(certiCodeAttr)) {
                KitePosAttrDTO custState = new KitePosAttrDTO();
                custState.setCode("certiCode");
                custState.setValue(Optional.ofNullable(custDto.getCertiCode()).orElse(""));
                custState.setStartDate(createDateStr);
                custState.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
                customer.getAttrs().add(custState);
            }
        }
        else {
            // 过户业务客户信息需要重新调整
            String newCustId = kiteSceneInst.getNewCustId();
            // 从缓存里面取
            Map<String, Object> extParameter = querySceneInstService.getExtParameter(sceneInstId);
            Object newCust = extParameter.get(sceneInstId + "_transNewCustDTO");
            CuccCustInfoDTO newCustDto = Objects.nonNull(newCust) ? (CuccCustInfoDTO) newCust
                : queryNewCustInfo(newCustId);
            KiteBeanUtils.copyProperties(newCustDto, customer);
            // add by sqy 2020.10.8 属性对不上，转换不了，做特殊处理
            customer.setContactName(newCustDto.getAddress());
            customer.setEparchyCity(newCustDto.getEparchyName());
            customer.setEparchyArea(newCustDto.getEparchyName());
            customer.setName(newCustDto.getCustName());
            customer.setCustStatus(newCustDto.getCustState());
            customer.setCustType(newCustDto.getCustType());
            customer.setEparchyProvince(newCustDto.getProvinceCode());
            customer.setAddress(newCustDto.getAddr());
            customer.setBssId(newCustDto.getBbssCustId());
            customer.setCbssId(newCustDto.getCustId());
            customer.setContactName(newCustDto.getContactName());
            customer.setCustType(custDto.getCustType());
            List<KitePosAttrDTO> attrs = new ArrayList<>();

            KitePosAttrDTO custIDAttrs = new KitePosAttrDTO();
            CustAttrDTO custAttrDTOs = this.getAttrByCode(custDto, "custState");
            KiteBeanUtils.copyProperties(custAttrDTOs, custIDAttrs);
            custIDAttrs.setValue(newCustDto.getCustState());
            custIDAttrs.setCode("custState");
            attrs.add(custIDAttrs);

            List<CustAttrDTO> custAttrs = newCustDto.getAttrs();
            if (KiteListUtils.isNotEmpty(custAttrs)) {
                custAttrs.forEach(custAttr -> {
                    KitePosAttrDTO attr = new KitePosAttrDTO();
                    KiteBeanUtils.copyProperties(custAttr, attr);
                    attrs.add(attr);
                });
            }
            // 需要加原来老客户属性,补充isDefaultAcct属性节点
            // 从缓存里面取
            List<InstAttrDTO> attrConfigs = queryScenePersonService
                .listKiteConfigAttrs(sceneInstId, LocalKeyConsts.TRANSFER_DISPLAY_OBJECT_TYPE).getResultObject()
                .stream()
                .filter(instAttrDTO -> LocalKeyConsts.KITE_ATTR_CONFIG_SHOW_TYPE_D.equals(instAttrDTO.getShowType()))
                .collect(Collectors.toList());
            if (KiteListUtils.isNotEmpty(attrConfigs)) {
                Map<String, String> orderAttrMap = new HashMap<String, String>();
                attrConfigs.forEach(orderAttr -> orderAttrMap.put(orderAttr.getFieldName(), orderAttr.getValue()));

                KitePosAttrDTO custIDAttr = new KitePosAttrDTO();
                CustAttrDTO custAttrDTO = this.getAttrByCode(custDto, "isDefaultAcct");
                KiteBeanUtils.copyProperties(custAttrDTO, custIDAttr);
                String isDefault = KiteStringUtils.isEqual(orderAttrMap.getOrDefault("is_trans_acct", "0"), "0") ? "2"
                    : "1";
                custIDAttr.setValue(isDefault);
                custIDAttr.setCode("isDefaultAcct");
                attrs.add(custIDAttr);
            }

            this.dealOldCustInfo(attrs, custDto);
            customer.setAttrs(attrs);
        }
        context.getPosDto().setCustomer(customer);
    }

    private CuccCustInfoDTO queryNewCustInfo(String custId) {
        KiteCustomerInfoReq kiteCustomerInfoReq = new KiteCustomerInfoReq();
        CuccCustInfoDTO cuccCustInfoDTO = new CuccCustInfoDTO();
        kiteCustomerInfoReq.setCustId(custId);
        String staffCode = ContextUtil.getSimpleLoginInfo().getStaffCode();
        String eparchyCode = ContextUtil.getSimpleLoginInfo().getLanId();
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        kiteCustomerInfoReq.setStaffCode(staffCode);
        kiteCustomerInfoReq.setEparchyCode(eparchyCode);
        kiteCustomerInfoReq.setProvinceCode(provinceCode);
        kiteCustomerInfoReq.setPageNum(1);
        kiteCustomerInfoReq.setPageSize(10);
        // 调用查询客户列表
        PageInfo<CuccCustInfoDTO> list = custReceptionService.customerListQueryNew(kiteCustomerInfoReq);
        if (!KiteObjectUtils.isEmpty(list) && KiteListUtils.isNotEmpty(list.getList())) {
            List<CuccCustInfoDTO> cuccCustInfoDTOList = list.getList();
            cuccCustInfoDTO = cuccCustInfoDTOList.get(0);
        }
        return cuccCustInfoDTO;
    }

    private void dealOldCustInfo(List<KitePosAttrDTO> attrs, CuccContextCustDTO custDto) {
        KitePosAttrDTO custIDAttr = new KitePosAttrDTO();
        CustAttrDTO custAttrDTO = this.getAttrByCode(custDto, "custId");
        KiteBeanUtils.copyProperties(custAttrDTO, custIDAttr);
        custIDAttr.setValue(custDto.getCustId());
        custIDAttr.setCode("oldCustId");
        attrs.add(custIDAttr);

        KitePosAttrDTO custNameAttr = new KitePosAttrDTO();
        custAttrDTO = this.getAttrByCode(custDto, "custName");
        KiteBeanUtils.copyProperties(custAttrDTO, custNameAttr);
        custNameAttr.setValue(custDto.getCustName());
        custNameAttr.setCode("oldCustName");
        attrs.add(custNameAttr);
        KitePosAttrDTO custStateAttr = new KitePosAttrDTO();
        custAttrDTO = this.getAttrByCode(custDto, "custState");
        KiteBeanUtils.copyProperties(custAttrDTO, custStateAttr);
        if (KiteStringUtils.isNotEmpty(custDto.getCustStatus())) {
            custStateAttr.setValue(custDto.getCustStatus());
            custStateAttr.setCode("oldCustState");
            attrs.add(custStateAttr);
        }
    }

    private CustAttrDTO getAttrByCode(CuccContextCustDTO custDto, String code) {
        if (Objects.isNull(custDto.getAttrs())) {
            CustAttrDTO custAttr = new CustAttrDTO();
            custAttr.setCode(code);
            custAttr.setStartDate(KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_TIME_FORMAT_14));
            custAttr.setEndDate(KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_TIME_FORMAT_14));
            return custAttr;
        }
        List<CustAttrDTO> custAttrList = custDto.getAttrs().stream().filter(oldAttr -> "code".equals(oldAttr.getCode()))
            .collect(Collectors.toList());
        return KiteListUtils.isNotEmpty(custAttrList) ? custAttrList.get(0) : new CustAttrDTO();

    }

    private CuccCustInfoDetailDTO getCustInfo(String custId) {
        String staffCode = ContextUtil.getSimpleLoginInfo().getStaffCode();
        String eparchyCode = ContextUtil.getSimpleLoginInfo().getLanId();
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        KiteCustomerInfoReq kiteCustomerInfoReq = new KiteCustomerInfoReq();
        kiteCustomerInfoReq.setStaffCode(staffCode);
        kiteCustomerInfoReq.setEparchyCode(eparchyCode);
        kiteCustomerInfoReq.setProvinceCode(provinceCode);
        kiteCustomerInfoReq.setCustId(custId);
        CuccCustInfoDetailDTO cuccCustInfoDTO = custReceptionService.getCustomerDetail(kiteCustomerInfoReq)
            .getResultObject();
        if (Objects.isNull(cuccCustInfoDTO)) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("提交订单失败，过户后的新客户信息不存在");
        }
        return cuccCustInfoDTO;
    }

}
